package com.cskaoyan.service.front.coupon;

import com.cskaoyan.bean.bo.front.coupon.SelectCouponUserBo;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.back.BaseRespVo;
import com.cskaoyan.bean.vo.back.admin.BaseDataVo;
import com.cskaoyan.bean.vo.front.coupon.CouponUserVo;
import com.cskaoyan.exception.MarketValidationException;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.util.DateFormatUtil;
import com.cskaoyan.util.IsCouponValid;
import com.cskaoyan.util.SessionUtil;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * wx优惠券服务impl
 *
 * @author 李然
 * @date 2022/10/15
 */

@Service
public class WxCouponServiceImpl implements WxCouponService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    /**
     * 优惠券用户列表
     *
     * @param couponBo 优惠券博
     * @return {@link BaseDataVo}
     */
    @Override
    public BaseDataVo getMyCouponUserList(SelectCouponUserBo couponBo) {
//        //        获取用户名
//
//        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
////        if (username == null || "".equals(username)) {
////            return null;
////        }
//        if(!ParamUtils.isValid(username)) {
//            return null;
//        }
//        MarketUserExample userExample = new MarketUserExample();
//        userExample.createCriteria().andUsernameEqualTo(username);
//
//        // TODO: 2022/10/14 是否需要静态注入
//        /**
//         * solution:
//         *      private static UserMapper staticUserMapper;
//         *      staticUserMapper = this.userMapper;
//         */
//        List<MarketUser> users = userMapper.selectByExample(userExample);
//
//        //拿到具体用户的登录信息
//        MarketUser marketUser = users.get(0);

        MarketUser marketUser = SessionUtil.getUserInfo();

        PageHelper.startPage(couponBo.getPage(), couponBo.getLimit());

        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andUserIdEqualTo(marketUser.getId())
                .andStatusEqualTo(couponBo.getStatus()).andDeletedEqualTo(false);
        //根据条件查询
        example.setOrderByClause("update_time desc");
        List<MarketCouponUser> couponUsers = marketCouponUserMapper.selectByExample(example);
        List<CouponUserVo> couponUsers1 = new ArrayList<>();
        //筛选过期的
        for (MarketCouponUser couponUser : couponUsers) {
            if (!IsCouponValid.judge(couponUser)) {
                couponUser.setStatus((short) 2);
                marketCouponUserMapper.updateByPrimaryKeySelective(couponUser);
                break;
            }
            //根据couponId
            MarketCoupon coupon = marketCouponMapper.selectByPrimaryKey(couponUser.getCouponId());
            CouponUserVo couponUserVo = new CouponUserVo(false, couponUser.getCouponId(), coupon.getDesc(), coupon.getDiscount(), couponUser.getEndTime(), couponUser.getId(), coupon.getMin(), coupon.getName(), couponUser.getStartTime(), coupon.getTag());
            couponUsers1.add(couponUserVo);
        }

        PageInfo<CouponUserVo> pageInfo = new PageInfo<>(couponUsers1);

        return new BaseDataVo(pageInfo, couponUsers1);
    }

    /**
     * 兑换
     *
     * @param code 代码
     * @return int
     */
    @Override
    public int exchange(String code) {

        MarketCouponExample example = new MarketCouponExample();

        example.createCriteria().andCodeEqualTo(code).andStatusEqualTo((short) 0);
        List<MarketCoupon> coupons = marketCouponMapper.selectByExample(example);
        if (coupons == null || coupons.size() == 0) {
            return 742;
        }
        MarketCoupon coupon = coupons.get(0);
        //判断优惠卷是否有效
        if (!IsCouponValid.judge(coupon)) {
            coupon.setStatus((short) 1);
            coupon.setUpdateTime(new Date());
            marketCouponMapper.updateByPrimaryKeySelective(coupon);
            return 742;
        }
        MarketUser userInfo = SessionUtil.getUserInfo();
        if (coupon.getTimeType() == 0) {
            coupon.setStartTime(new Date());
            coupon.setEndTime(DateFormatUtil.endTime(coupon.getStartTime(), coupon.getDays()));
        }
        MarketCouponUser record = new MarketCouponUser(null, userInfo.getId(), coupon.getId(), (short) 0, null, coupon.getStartTime(), coupon.getEndTime(), null, new Date(), new Date(), false);
        marketCouponUserMapper.insertSelective(record);

        //减库存
        MarketCoupon record2 = new MarketCoupon();
        record2.setId(coupon.getId());
        record2.setTotal(coupon.getTotal() - 1);
        record2.setUpdateTime(new Date());
        marketCouponMapper.updateByPrimaryKeySelective(record2);
        return 0;
    }

    /**
     * 获得优惠券
     *
     * @param couponId 优惠券id
     * @return int
     */
    @SneakyThrows
    @Override
    public BaseRespVo receiveCoupon(Integer couponId) {

        //先拿到用户信息
        MarketUser userInfo = SessionUtil.getUserInfo();
        //先查询两个表的信息
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andCouponIdEqualTo(couponId).andUserIdEqualTo(userInfo.getId());

        List<MarketCouponUser> couponUsers = marketCouponUserMapper.selectByExample(example);
        MarketCoupon coupon = marketCouponMapper.selectByPrimaryKey(couponId);
        //判断领取限制
        if (coupon.getLimit() != 0) {
            if (couponUsers != null && couponUsers.size() == coupon.getLimit()) {
//                throw new MarketValidationException("领取已达上限！");
                return BaseRespVo.couponError(740,"优惠券已经领取过！");

            }
        }
        //判断优惠券库存
        if (coupon.getTotal() == 0) {
//            throw new MarketValidationException("优惠券已领完！");
            return BaseRespVo.couponError(740,"优惠券已领完！");
//            return 740;
        }
        if (!IsCouponValid.judge(coupon)) {
//            throw new MarketValidationException("优惠券已过期！");
            return BaseRespVo.couponError(740,"优惠券已过期！");

        }
        if (coupon.getTimeType() == 0) {
            coupon.setStartTime(new Date());
            coupon.setEndTime(DateFormatUtil.endTime(coupon.getStartTime(), coupon.getDays()));
        }
        MarketCouponUser record = new MarketCouponUser(null, userInfo.getId(), couponId, (short) 0, null, coupon.getStartTime(), coupon.getEndTime(), null, new Date(), new Date(), false);
        marketCouponUserMapper.insertSelective(record);
        //减库存
        MarketCoupon record1 = new MarketCoupon();
        record1.setId(couponId);
        record1.setUpdateTime(new Date());
        record1.setTotal(coupon.getTotal() - 1);
        marketCouponMapper.updateByPrimaryKeySelective(record1);
//        return 0;
        return BaseRespVo.ok();
    }

    /**
     * 得到wx优惠券列表
     *
     * @param param 参数
     * @return {@link BaseDataVo}<{@link MarketCoupon}>
     */
    @Override
    public BaseDataVo<MarketCoupon> getWxCouponList(BaseParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        MarketCouponExample example = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo((short) 0).andDeletedEqualTo(false).andTypeEqualTo((short) 0);
        example.setOrderByClause("add_time desc");

//        查询数据库并筛选参数正确的优惠券
        List<MarketCoupon> coupons = marketCouponMapper.selectByExample(example);
        List<MarketCoupon> coupons2 = new ArrayList<>();
        for (MarketCoupon coupon : coupons) {
            if (!IsCouponValid.judge(coupon)) {
                coupon.setStatus((short) 1);
                marketCouponMapper.updateByPrimaryKey(coupon);
                break;
            }
            coupons2.add(coupon);
        }

        PageInfo<MarketCoupon> pageInfo = new PageInfo<>(coupons2);

        return new BaseDataVo<>(pageInfo, coupons2);
    }

    /**
     * 选择优惠券列表
     *
     * @param cartId 购物车id
     * @return {@link BaseDataVo}
     */
    @Override
    public BaseDataVo selectCouponList(Integer cartId) {
        MarketUser userInfo = SessionUtil.getUserInfo();
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andStatusEqualTo((short) 0).andUserIdEqualTo(userInfo.getId());
        List<MarketCouponUser> couponUsers = marketCouponUserMapper.selectByExample(example);

//
        List<CouponUserVo> availableCoupon = IsCouponValid.getAvailableCoupon(couponUsers, userInfo.getId(), cartId);

        return new BaseDataVo(availableCoupon.size(), 1, availableCoupon.size(), 1, availableCoupon);
    }
}
